package com.itheima.controller;

import com.alibaba.fastjson.JSONObject;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/setmeal/")
public class SetmealController {

    @Reference(timeout = 7000)
    private SetmealService setmealService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String SETMEAL = "SETMEAL_FIND_PAGE";

    @RequestMapping("findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        PageResult pageResult = null;
        try {
            String hashKey = queryPageBean.getCurrentPage()+":"+queryPageBean.getPageSize();
            HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
            Object data = hash.get(SETMEAL,hashKey);
            if(data == null){
                pageResult = setmealService.pageQuery(queryPageBean);
                hash.put(SETMEAL,hashKey,pageResult);
            }else{
                pageResult = ((JSONObject)data).toJavaObject(PageResult.class);
            }
        } catch (Exception e) {
            pageResult = setmealService.pageQuery(queryPageBean);
        }

        return pageResult;
    }

    @RequestMapping("findById")
    public Result findById(Integer id){
        try {
            Setmeal setmeal = setmealService.findById(id);
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);

        }
    }

}
